package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import org.apache.tomcat.jni.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@RequestMapping("/addressBook")
@RestController
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;
    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook, HttpSession session) {
        Long empId = (Long) session.getAttribute("user");
        addressBook.setUserId(empId);
        addressBook.setCreateTime(LocalDateTime.now());
        addressBook.setUpdateTime(LocalDateTime.now());
        addressBook.setCreateUser(empId);
        addressBook.setUpdateUser(empId);
        addressBookService.save(addressBook);
        return R.success("保存成功");
    }

    @GetMapping("/list")
    public R<List<AddressBook>> list(HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        List<AddressBook> addressBookList = addressBookService.list(userId);
        return R.success(addressBookList);
    }

    /**
     * 根据id查询地址
     */
    @GetMapping("/{id}")
    public R<AddressBook> findById(@PathVariable Long id){
        AddressBook addressBook = addressBookService.findById(id);
        if(addressBook != null){
            return R.success(addressBook);
        }else {
            return R.error("没有找到该对象");
        }
    }

    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook,HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        addressBook.setUpdateUser(userId);
        addressBookService.update(addressBook);
        return R.success("修改成功");
    }

    @PutMapping("/default")
    public R<AddressBook> updateDefault(@RequestBody AddressBook addressBook, HttpSession session) {
        Long userId = (Long) session.getAttribute("user");
        addressBook.setUserId(userId);
        addressBook.setUpdateTime(LocalDateTime.now());
        addressBook.setUpdateUser(userId);
        addressBookService.updateDefault(addressBook);
        return R.success(addressBook);
    }
    /**
     * 查询默认地址
     */
    @GetMapping("default")
    public R<AddressBook> getDefault(HttpSession session) {
        Long userId = (Long) session.getAttribute("user");
        AddressBook addressBook = addressBookService.getDefaultAddress(userId);

        if (null == addressBook) {
            return R.error("没有找到该对象");
        } else {
            return R.success(addressBook);
        }
    }

    @DeleteMapping
    public R<String> deleteById(Long ids){
        addressBookService.deleteById(ids);
        return R.success("删除地址成功");
    }





}
